package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.enums.FlowStatusEnum;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdTrustTeam;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import java.io.PrintWriter;
import net.sf.json.JSONObject;
import java.nio.charset.StandardCharsets;
import com.ccp.dev.qbdms.model.WQbdQualityteamDec;
import com.ccp.dev.qbdms.service.WQbdQualityteamDecService;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.core.basic.annotion.Action;

import java.util.*;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.ModelMap;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.poi.excel.editor.IFontEditor;
import com.ccp.dev.core.poi.excel.style.Color;
import com.ccp.dev.core.poi.excel.style.DataFormat;
import com.ccp.dev.core.poi.excel.style.font.BoldWeight;
import com.ccp.dev.core.poi.excel.style.font.Font;
import com.ccp.dev.core.poi.excel.util.ExcelUtil;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.util.BaseUtil;

/**
 * 质量信得过班组申报 信息操作处理控制器
 * 
 * @author 于金
 * @date 2020-10-12 15:30:53
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "质量信得过班组申报")
@RequestMapping("/qbdms/wQbdQualityteamDec")
public class WQbdQualityteamDecController extends SysBaseController{
    @Resource
    private WQbdQualityteamDecService wQbdQualityteamDecService;
    @Resource
    private WCustomColumnsService wCustomColumnsService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: 于金
     * @date: 2020-10-12 15:30:53
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到质量信得过班组申报首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, ModelMap modelMap) {
        wCustomColumnsService.addCustomCols(request);
        // 当前系统等级
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        modelMap.put("currentSystemLevel", currentSystemLevel);
        // 当前登录用户id
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        return "wQbdQualityteamDec/list";
    }

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: 于金
    * @date: 2020-10-12 15:30:53
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询质量信得过班组申报",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        // 默认按照评定时间倒序排列,评定时间相同的情况下按创建时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "CREATETIME");
            queryFilter.addFilter("orderSeq", "desc");
        }
        // 添加通用查询条件
        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<WQbdQualityteamDec> pageDatas = wQbdQualityteamDecService.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        // 添加编辑按钮权限控制
        ZhiLiangConst.isDataAllowEditByFlowStatus(pageDatas);
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: 于金
     * @date: 2020-10-12 15:30:53
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到质量信得过班组申报新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        return "wQbdQualityteamDec/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wQbdQualityteamDec 保存的对象
    * @return: java.lang.Object
    * @auther: 于金
    * @date: 2020-10-12 15:30:53
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存质量信得过班组申报数据",detail="<#if isAdd>新增<#else>编辑</#if>质量信得过班组申报数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>成功></#if>")
    public Object save(@RequestBody WQbdQualityteamDec wQbdQualityteamDec) {
        String id = wQbdQualityteamDec.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            //新增数据前生成随机Id
            wQbdQualityteamDec.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdQualityteamDec);
            //上报状态
            BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
            if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(currentSystemLevel)) {
                wQbdQualityteamDec.setReportStatus(ZhiLiangConst.HOSPITAL_INTERNALAPPROVAL_THEAPPROVALISPENDING);
            } else if (BaseUtil.SystemLevel.PLANTLEVEL.equals(currentSystemLevel)) {
                wQbdQualityteamDec.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            }
            result = wQbdQualityteamDecService.add(wQbdQualityteamDec);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdQualityteamDec);
            result = wQbdQualityteamDecService.update(wQbdQualityteamDec);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdQualityteamDecService.getOneById(id), wQbdQualityteamDec));
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: 于金
    * @date: 2020-10-12 15:30:53
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到质量信得过班组申报详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        return "wQbdQualityteamDec/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: 于金
    * @date: 2020-10-12 15:30:53
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询质量信得过班组申报的一条数据",detail="根据主键id查询质量信得过班组申报的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdQualityteamDec wQbdQualityteamDec = wQbdQualityteamDecService.getOneById(id);
        if (null == wQbdQualityteamDec) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdQualityteamDec);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: 于金
    * @date: 2020-10-12 15:30:53
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除质量信得过班组申报数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdQualityteamDec wQbdQualityteamDec = wQbdQualityteamDecService.getOneById(key);
            if (!userId.equals(wQbdQualityteamDec.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败！只能删除自己创建的数据！");
            }
            if (!FlowStatusEnum.getEnumByValue(wQbdQualityteamDec.getFlowStatus()).isDel()) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败！不允许删除流程未结束数据！");
            }
//            if (Objects.nonNull(wQbdTrustTeam.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(wQbdTrustTeam.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED.equals(wQbdTrustTeam.getReportStatus())) {
//                SysAuditThreadLocalHolder.putParamerter("success", false);
//                return fail("删除失败，只允许删除待上报的数据");
//            }
        }

        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        int result = wQbdQualityteamDecService.delByIdArray(id.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
    * 功能描述: 跳转到导入页面
    *
    * @return: java.lang.String
    * @auther: 于金
    * @date: 2020-10-12 15:30:53
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到质量信得过班组申报导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdQualityteamDec/import";
    }

    /**
    * 功能描述: 跳转到导出选择字段页面
    *
    * @param: [request] http请求
    * @param: modelMap
    * @return: java.lang.String
    * @auther: 于金
    * @date: 2020-10-12 15:30:53
    * @throws Exception
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到质量信得过班组申报导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdQualityteamDec.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }

    /**
    * 功能描述: 导出质量信得过班组申报数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: 于金
    * @date: 2020-10-12 15:30:53
    */
    @RequestMapping("/exportData")
    @Action(description="导出质量信得过班组申报数据信息",detail="导出质量信得过班组申报数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        // 默认按照评定时间倒序排列,评定时间相同的情况下按创建时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "CREATETIME");
            queryFilter.addFilter("orderSeq", "desc");
        }
        List<WQbdQualityteamDec> list = this.wQbdQualityteamDecService.queryAll(queryFilter);

        if (list.isEmpty()) {
            list.add(new WQbdQualityteamDec());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, list, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
    * 导入资源文件
    * @param request
    * @param response
    * @throws Exception
    */
    @RequestMapping("/importData")
    @ResponseBody
    public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
        Map<String, Object> map = new AbstractImpUtil(){
            @Override
            public ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;
                return returnType;
            }
        }.reverseModels(excelEntity, WQbdQualityteamDec.class);
        String msg = map.get("msg").toString();
        List<WQbdQualityteamDec> list = (List<WQbdQualityteamDec>) map.get("instList");
        if (StringUtil.isEmpty(msg)) {
            this.wQbdQualityteamDecService.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("dataSource.importXml.success");
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail(msg);
        }
    }


    /**
    * 查询上报的信息
    *
    * @param id        业务数据主键
    * @param tableName 业务表名
    * @return
    */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(@RequestParam("id") String id, @RequestParam("tableName") String tableName) throws IllegalAccessException {
        //业务数据
        List<WQbdQualityteamDec> reportList = wQbdQualityteamDecService.reportList(id, tableName);
        ZhiLiangConst.showName(reportList);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }

}
